package cn.edu.tju.fctl.rest;

import cn.edu.tju.fctl.entities.User;
import cn.edu.tju.fctl.service.IUserService;
import cn.edu.tju.fctl.service.IVacationService;
import cn.edu.tju.fctl.util.*;
import com.sun.jersey.multipart.FormDataParam;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;

/**
 * Created by catold
 */
@Component
@Path("user")
public class UserRest {
    public static final Logger LOGGER = LoggerFactory.getLogger(UserRest.class);
    @Autowired
    IUserService userService;
    @Autowired
    IVacationService vacationService;

    @Path("/login")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Object userLogin(@QueryParam("number") final String username,
                            @QueryParam("pwd") final String password) {
        Object response = new Object();
        try {
            ShiroUtil.login(username, password);
            response = ShiroUtil.getUser();
        } catch (UnknownAccountException uae) {
            response = StateCode.buildCode(BizCode.UNKNOWNACCOUNT);
        } catch (IncorrectCredentialsException ice) {
            response = StateCode.buildCode(BizCode.INCORRECTPASSWORD);
        } catch (Exception e) {
            response = StateCode.buildCode(BizCode.FAIL);
        }
        return response;
    }

    @Path("/logout")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Object userLogout() {
        Object response = new Object();
        ShiroUtil.logout();
        response = StateCode.buildCode(BizCode.SUCCESS);
        return response;
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Object getUserInfo() {
        return ShiroUtil.getUser();
    }

    @Path("/pwd")
    @PUT
    @Produces(MediaType.APPLICATION_JSON)
    public Object changePassword(@QueryParam("newpwd") final String newpwd,
                                 @QueryParam("oldpwd") final String oldpwd) {
        User user = ShiroUtil.getUser();
        StateCode stateCode;
        try {
            if (!user.getPwd().equals(oldpwd)) {

                return StateCode.buildCode(BizCode.USER_OLDPWD_WRONG);
            } else {
                User user1 = userService.findById(user.getUserId());
                user1.setPwd(newpwd);
                userService.updateUser(user1);
                ShiroUtil.setUser(user1);
                stateCode = StateCode.buildCode(BizCode.SUCCESS);
            }
        } catch (Exception e) {
            e.printStackTrace();
            stateCode = StateCode.buildCode(BizCode.FAIL);
        }
        return stateCode;
    }

    @PUT
    @Path("/info")
    @Consumes(MediaType.APPLICATION_JSON)
    public Object changeUserInfo(@QueryParam("phone") String phone, @QueryParam("email") String email) {
        Object response = new Object();
        User user = ShiroUtil.getUser();
        if(phone != null && !phone.isEmpty())
            user.setPhone(phone);
        if(email != null && !email.isEmpty())
            user.setEmail(email);

        userService.updateUser(user);
        ShiroUtil.setUser(user);
        response = StateCode.buildCode(BizCode.SUCCESS);
        return response;
    }

    @Path("/avator/{avator_url}")
    @PUT
    @Produces(MediaType.APPLICATION_JSON)
    public Object changeAvator(@PathParam("avator_url") final String avator_url) {
        Object response = new Object();
        User user = ShiroUtil.getUser();
        user.setAvatorImg(avator_url);
        userService.updateUser(user);
        response = StateCode.buildCode(BizCode.SUCCESS);
        return response;
    }

    @Path("/own_vacation")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Object getOwnVacation(@QueryParam("page") final int PAGE,
                                 @QueryParam("num") final int NUM) {
        Object response = new Object();
        User user = ShiroUtil.getUser();
        response = vacationService.findAllVacationByApproverID(user.getUserId(), PAGE, NUM);

        return response;
    }

    @Path("/evaluation")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Object getEvaluation(@QueryParam("fromyear") final int FROMYEAR,
                                @QueryParam("frommonth") @DefaultValue("-1") final int FROMMONTH,
                                @QueryParam("toyear") final int TOYEAR,
                                @QueryParam("tomonth") @DefaultValue("-1") final int TOMONTH) {
        Object response = new Object();
        try {
            User user = ShiroUtil.getUser();
            response = vacationService.getEvaluation(user.getUserId(),FROMYEAR,FROMMONTH,TOYEAR,TOMONTH);
        }catch(Exception e){
            //response = EvaluationUtil.getEvaluation(user.getUserId(),FROMYEAR,FROMMONTH,TOYEAR,TOMONTH);
            response = StateCode.buildCode(BizCode.FAIL);
            e.printStackTrace();
        }
        return response;
    }

    @Path("/amount")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Object getAllEvaluation(@QueryParam("fromyear") final int FROMYEAR,
                                @QueryParam("frommonth") @DefaultValue("-1") final int FROMMONTH,
                                @QueryParam("toyear") final int TOYEAR,
                                @QueryParam("tomonth") @DefaultValue("-1") final int TOMONTH,
                                   @QueryParam("depart_id") final int DEPARTID,
                                   @QueryParam("email") final String email) {
        Object response = new Object();
        try {
//            User user = ShiroUtil.getUser();
//            response = vacationService.getEvaluation(user.getUserId(),FROMYEAR,FROMMONTH,TOYEAR,TOMONTH);
            EmailUtil.sendOneMail(email, "统计报表", ShiroUtil.getUser().getName() + "给您统计的报表:  " + SystemConfig.SERVER + "/file/excel?depart_id=" + DEPARTID + "&fromyear=" + FROMYEAR + "&toyear=" + TOYEAR + "&tomonth=" + TOMONTH + "&frommonth=" + FROMMONTH + " ");
            response = StateCode.buildCode(BizCode.SUCCESS);
        }catch(Exception e){
            //response = EvaluationUtil.getEvaluation(user.getUserId(),FROMYEAR,FROMMONTH,TOYEAR,TOMONTH);
            response = StateCode.buildCode(BizCode.FAIL);
            e.printStackTrace();
        }
        return response;
    }

    @Path("/noop")
    @OPTIONS
    @Produces(MediaType.APPLICATION_JSON)
    public Object noop() {
        return StateCode.buildCode(BizCode.SUCCESS);
    }

    @GET
    @Path("/mark")
    @Produces(MediaType.APPLICATION_JSON)
    public Object getMarks(){
        return userService.findUserMarks(ShiroUtil.getUser().getUserId());
    }
}
